package ru.amse.jsynchro.kernel.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import ru.amse.jsynchro.fileSystem.FileSystem;
import ru.amse.jsynchro.kernel.Difference;
import ru.amse.jsynchro.kernel.Operation;
import ru.amse.jsynchro.logging.ILogger;

/**
 * The task implements action of adding
 * missing in second folder file from 
 * the first one.
 *  
 * @author miha
 *
 */
public class DirectedTask extends Task {
    private List<Difference> secondDiffs;
    
    public DirectedTask(String firstFolder, FileSystem fs1, 
                        String secondFolder, FileSystem fs2, 
                        boolean forceResolveConflicts, ILogger logger) throws IOException {
        super(firstFolder, fs1, secondFolder, fs2, forceResolveConflicts, logger);
    }    
    
    public boolean analyze() {
        secondDiffs = first.compare(second, false);
        List<Difference> atomic = new ArrayList<Difference>();
        first.addAtomicDiffs(secondDiffs, atomic, false);
        secondDiffs = atomic;
        return getDiffsNumber() > 0;
    }
    
    public void synchronize() {
        applyChanges(secondDiffs, first, second);
    }
    
    protected void resolveConflicts() {
        Scanner sc = new Scanner(System.in);
        for (Difference diff: secondDiffs) {
            if (diff.getOperation() == Operation.CONFLICT) {
                if (forceResolveConflicts) {
                    diff.setOperation(Operation.ADD);
                } else {
                    System.out.println(diff);
                    System.out.println("resolve conflict update" +
                            " in Second, Nothing (S, N) ");
                    String answer = sc.nextLine();
                    answer = answer.toUpperCase();
                    char c = answer.charAt(0);
                    switch (c) {
                        case 'S': diff.setOperation(Operation.ADD);break;
                        case 'N': diff.setOperation(Operation.NOTHING);break;
                        default: diff.setOperation(Operation.NOTHING);break;
                    }
                }
            }
        }
        sc.close();
    }
    
    public int getDiffsNumber() {
        return secondDiffs.size();
    }
    
    public List<String> getStringDifferences() {
        List<String> result = new ArrayList<String>();        
        makeStringDifferences(second.getPath(), secondDiffs, result);
        return result;
    }
    
}
